package com.concurrent.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author: zhouyang
 * @descrpition: CyclicBarrier Demo
 * @time: 2019-05-08 14:09
 */
@Slf4j
public class CyclicBarrierTest {
    private static CyclicBarrier cyclicBarrier = new CyclicBarrier(5);
    public static void main(String[] args)throws Exception{
        ExecutorService executorService = Executors.newCachedThreadPool();
        for(int i=0;i<100;++i){
            Thread.sleep(1000);
            final int now = i;
            executorService.execute(()->{
                try {
                    barrier(now);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
        executorService.shutdown();
    }

    private static void barrier(final int threadNum)throws Exception{
        log.info("thread {} ready",threadNum);
        Thread.sleep(2000);
        cyclicBarrier.await();
        log.info("thread {} continue",threadNum);
    }
}
